import router from "@/router/index.js";
import errorHandler from "@/utils/errorHandler.js";
import {localSecretStorage, sessionSecretStorage} from "@/utils/ls.js";
import axios from "axios";
import {ElMessage} from "element-plus";

const instance = axios.create({
    baseURL: "/api",
    timeout: 6000,
});

instance.interceptors.request.use(
    (config) => {
        if (config.url === "/auth/login") {
            return {...config, timeout: 10000};
        }
        const token =
            localSecretStorage.get("token") || sessionSecretStorage.get("token");
        if (token) {
            config.headers.Authorization = `${token}`;
            return config;
        } else {
            ElMessage.error("未找到认证令牌，请先登录");
            router.push("/login")
            return Promise.reject(new Error("未找到认证令牌，请先登录"));
        }
    },
    (error) => {
        console.error("Request Error:", error);
        ElMessage.error("请求错误，请稍后重试！: " + error.message);
        return error;
    }
);

instance.interceptors.response.use(
    (response) => {
        if (response.data.code === 401) {
            sessionStorage.removeItem("token");
            router.replace("/login").then(() => {
                ElMessage.closeAll();
                ElMessage.error(response.data.message);
            });
            return Promise.reject(new Error(response.data));
        }
        return response.data;
    },
    (error) => {
        error = errorHandler(error);
        return Promise.reject(new Error(error));
    }
);

export default instance;
